//
//  MineRegViewController.swift
//  House
//
//  Created by 吕品 on 16/7/1.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import UIKit
import MBProgressHUD
import SafariServices
import RxCocoa
import RxSwift
class MineRegViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, MixViewProtocol {

    var tableView = UITableView()
    var placeArray = [String]()
    var imageArray = [UIImage]()
    var selecet = true
    var mobileNum : String = ""
    var yzm : String = ""
    var naviBar = BaseTitleNavigationBar()
    
    var mixView = ImageViewAndTextFieldMixView()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tabBarController?.tabBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        tabBarController?.tabBar.isHidden = false
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        placeArray = ["请输入手机号", "请输入验证码", "请输入密码", "请再次输入密码"]
        imageArray = [UIImage.init(named: "MinePhoneNumber")!, UIImage.init(named: "MineCodeImage")!, UIImage.init(named: "MinePassword")!, UIImage.init(named: "MinePassword")!]
        naviBar = BaseTitleNavigationBar.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 64), withTitleStr: title)
        let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(back(tap:)))
        naviBar.leftView.addGestureRecognizer(tap1)
        view.addSubview(naviBar)
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 64, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 64), style: .plain)
        view.addSubview(tableView)
        tableView.backgroundColor = UIColor.groupTableViewBackground
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(ReuseImageViewAndTextFieldTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(ReuseImageViewAndTextFieldTableViewCell.self))
        let footView = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200))
//        mixView = ImageViewAndTextFieldMixView.init(frame: .zero)
        tableView.tableFooterView = footView
        let imageView = UIImageView.init(image: #imageLiteral(resourceName: "MineSelectedImage"))
        let button = UIButton.init(type: .custom)
        footView.addSubview(imageView)
        footView.addSubview(button)
        imageView.snp.makeConstraints { (make) in
            make.top.equalTo(footView.snp.top).offset(20)
            make.left.equalTo(footView.snp.left).offset(20)
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        button.snp.makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.left.equalTo(imageView.snp.right)
            make.bottom.equalTo(imageView)
            make.right.equalTo(footView.snp.right).offset(-20)
        }
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(MineRegViewController.agreeComment))
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
        button.titleLabel?.textAlignment = .left
        button.tintColor = .black
        let attrbuitText = NSMutableAttributedString(string: "同意<爱租房用户协议>")
        button.setAttributedTitle(attrbuitText, for: .normal)
        button.addTarget(self, action: #selector(MineRegViewController.jumpToAgreement), for: .touchUpInside)
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -60, 0, 0)



        let submitButton = UIButton.init(type: .custom)
        footView.addSubview(submitButton)
        submitButton.addTarget(self, action: #selector(MineRegViewController.submitInfo(_:)), for: .touchUpInside)
        submitButton.setTitle(title == "立即注册" ? "立即注册" : "立即找回", for: .normal)
        submitButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(footView)
            make.height.equalTo(60)
            make.width.equalTo(view).multipliedBy(0.7)
            make.top.equalTo(button.snp.bottom).offset(20)
        }
        submitButton.backgroundColor = naviColor
        submitButton.tintColor = .white
        submitButton.layer.masksToBounds = true
        submitButton.layer.cornerRadius = 4
        // Do any additional setup after loading the view.
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeArray.count
    }
    //agree agreement
    func agreeComment(_ tap: UITapGestureRecognizer) -> Swift.Void {
        selecet = !selecet
        let imageView: UIImageView = tap.view as! UIImageView
        imageView.image = selecet ? UIImage.init(named: "MineSelectedImage") : UIImage.init(named: "MineUnSelectedImage")
    }
    //submit
    func submitInfo(_ button: UIButton) -> Void {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        let cell0 = (view.viewWithTag(1000) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//phonenumb
        let cell1 = (view.viewWithTag(1001) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//yzm
        let cell2 = (view.viewWithTag(1002) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//password
        let cell3 = (view.viewWithTag(1003) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//password again
        if cell0 != "" && cell1 != "" && cell2 != "" && cell3 != "" {
            if cell1 == yzm && mobileNum == cell0 && yzm != ""{
                if cell2 != cell3 {
                    self.hide(withTitle: "两次输入的密码不一致")

                } else {
                    if !selecet {
                        self.hide(withTitle: "请先同意用户协议")

                    } else {
                        let bool = title == "立即注册"
                        let php = bool ? PHPHeader.manager().regPHP : PHPHeader.manager().forgetPasswordPHP
                        let alert = bool ? "注册" : "找回"

                        NetRequest.updateOrGetInformation(fromUrl: php, withParameters: ["act": "act", "tel": cell0, "pwd": cell2, "repwd":cell3] , success: { (task, response) in

                            if response != nil {
                                hud.mode = .text
                                if response is NSDictionary {
                                    let responseObject = response as! NSDictionary
                                    switch (responseObject["flg"] as! NSNumber).description as String {
                                    case "1":
                                        self.hide(withTitle: "成功")
                                        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { 
                                            print(self.navigationController?.popToRootViewController(animated: true))
                                        })
                                        break
                                    case "3" :
                                        self.hide(withTitle: "号码已经存在")
                                        break
                                    default:
                                        self.hide(withTitle: alert + "失败")
                                        break
                                    }
                                }

                            } else {
                                self.hide(withTitle: alert + "失败")

                            }
                            }, failure: { (task, error) in
                                self.hide(withTitle: alert + "失败")

                        })
                    }

                }

            } else {
                self.hide(withTitle:"验证码或手机号有误")

            }
        } else {
            self.hide(withTitle: "请将信息填写完整")

        }
    }
    func didPassValue(isSure: Bool) {
        if isSure {
            getCode()
        } else {
            let hud = MBProgressHUD.showAdded(to: view, animated: true)
            hud.mode = .text
            hud.label.text = "请输入正确的手机号"
            self.hide(withTitle: "请输入正确的手机号")
        }
    }
    //jumptoagreement
    func jumpToAgreement() -> Void {
        print("注册协议")
        let vc = SFSafariViewController.init(url: URL.init(string: "http://aizufang.hrbzjwl.com/tp/index.php/Home/User/xieyi")!)
        vc.title = "用户协议"
        present(vc, animated: true) { 
            
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(ReuseImageViewAndTextFieldTableViewCell.self)) as! ReuseImageViewAndTextFieldTableViewCell
        if indexPath.row == 0 {
            let _ = cell.mixView.textField.rx.text.subscribe(onNext: { (text) in
                print(text)
                if text != "" {
                    let cell = self.view.viewWithTag(1001) as! ReuseImageViewAndTextFieldTableViewCell
                    cell.isSure = RegConditionManager.checkPhoneNumber(text)
                }
                }, onError: { (error) in

                }, onCompleted: { 

                }, onDisposed: { 

            })
        }
        cell.mixView.imageView.image = imageArray[(indexPath as NSIndexPath).row]
        cell.mixView.textField.placeholder = placeArray[(indexPath as NSIndexPath).row]
        cell.mixView.isShowButton = false
        cell.mixView.textField.clearButtonMode = .always
        cell.mixView.textField.clearsOnBeginEditing = false
        if (indexPath as NSIndexPath).row == 1 {
            cell.mixView.isShowButton =  true
            cell.delegate = self
        }
        if (indexPath as NSIndexPath).row == 3 || (indexPath as NSIndexPath).row == 2 {
            cell.mixView.textField.isSecureTextEntry = true
        }
        cell.selectionStyle = .none
        cell.tag = (indexPath as NSIndexPath).row + tagManager
        return cell
    }

    //获取验证码
    func getCode() -> Void {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        let phone = (view.viewWithTag(1000) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//第一行手机号码
        if phone != "" {
            mobileNum = phone
            hud.label.text = "正在获取验证码,请稍后~"
            NetRequest.updateOrGetInformation(fromUrl: PHPHeader.manager().yzmRogerPHP, withParameters: ["mobile": phone] , success: { (task, responseObj) in
                print(responseObj)
                if responseObj is NSDictionary {
                    let response = responseObj as! NSDictionary
                    self.yzm = (response["yzm"] as! NSNumber).description
                    self.hide(withTitle: "获取成功")
                }

            }) { (task, error) in
                self.hide(withTitle: "获取失败,请稍后再试")
            }
        } else {
            self.hide(withTitle: "请输入正确的手机号")
        }
        //先讲号码记住防止用户更改后在注册

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
    @objc func back(tap: UITapGestureRecognizer) -> Void {
        self.navigationController!.popViewController(animated: true)
    }
    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
